<template>
    <div>
        <van-address-edit :area-list="areaList" :addressInfo="editAddressInfo" show-postal show-delete show-set-default
            @delete="onDelete" @change-area="changeArea" @change-default="changeDefault" @save="onSave"
            :area-columns-placeholder="['请选择', '请选择', '请选择']" />
    </div>
</template>

<script>
import { areaList } from "@vant/area-data";
import { fetchDeleteAddress, fetchUpdateAddress } from "../api/address.js";
export default {
    props: {
        // prop是只读的，不能改
        // 传来的地址信息
        addressInfo: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            areaList,
            editAddressInfo: {},
            areaCode: "", // 记录省市区编码 格式： 110000-111200-111233
            isDefault: null
        };
    },
    created() {
        this.editAddressInfo = JSON.parse(this.addressInfo);
        // console.log(222)
        // 记录默认的省市区编码
        this.areaCode = this.editAddressInfo.fullAreaCode;
        // 记录默认的地址
        this.isDefault = this.editAddressInfo.isDefault ? 1 : 0;
    },
    methods: {
        async onDelete() {
            let { status, message } = await fetchDeleteAddress(
                this.editAddressInfo.id
            );
            if (status == 0) {
                this.$router.back();
            }
            this.$toast(message);
        },
        async onSave(addressInfo) {
            let editAddressInfo = {
                ...addressInfo,
                areaCode: this.areaCode,
                isDefault: this.isDefault,
                country: addressInfo.county
            }

            // 调用接口更新地址
            let { status, message } = await fetchUpdateAddress(editAddressInfo.id, editAddressInfo)
            this.$toast(message)
            if (status === 0) {
                this.$router.back()
            }
        },

        // 切换省市区会去切换
        changeArea(values) {
            this.areaCode = values.map(item => item.code).join("-");
        },
        // 切换默认地址
        changeDefault(isDefault) {

            this.isDefault = isDefault ? 1 : 0;
        }
    }
};
</script>

<style lang="scss" scoped>
</style>
